package org.feng.exception;

import lombok.extern.slf4j.Slf4j;
import org.feng.pojo.Result;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * 全局异常处理器
 *
 * @author by feng
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result<String> methodArgumentNotValidException(MethodArgumentNotValidException exception) {
        BindingResult bindingResult = exception.getBindingResult();
        StringBuilder message = new StringBuilder();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            message.append(fieldError.getDefaultMessage()).append(";");
        }
        log.error(message.toString());
        exception.printStackTrace();
        return Result.error(message.toString());
    }

    @ExceptionHandler(value = ServiceException.class)
    public Result<String> serviceHandler(ServiceException exception) throws Exception {
        log.error("业务错误----错误编码：[{}]，错误信息：[{}]", exception.getCode(), exception.getMsg());
        exception.printStackTrace();
        return Result.error(exception.getCode(), exception.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    public Result<String> handler(Exception exception) throws Exception {
        log.error("系统错误----错误类型：[{}]，错误信息：[{}]", exception.getClass(), exception.getMessage());
        exception.printStackTrace();
        return Result.error(exception.getMessage());
    }


}
